/** dev server @author dongls */
process.env.NODE_ENV = 'development'

const inquirer = require('inquirer')
const colors = require('colors')
const koaWebpack = require('publink-koa-webpack')

const util = require ('../config/util')

const modulesData = require('../modules/index')
const server = require('../server')
const moduleMap = require('./model/moduleMap')
const { getObjectItemMaxLength } = require('./util/object')
const { completeString } = require('./util/string')

const { exec } = require('child_process')

const webpackDevConfig = require('../config/webpack.deve.conf')
const koaWebpackConfig = {
  config: webpackDevConfig,
  devMiddleware: {
    watchOptions: {
      // The default
      aggregateTimeout: 1500,
      ignored: ['dist', 'public', 'node_modules', 'script', 'server', 'cli', 'config']
    }
  },
  // IE11对websocket报SecurityError
  // 解决方案： Internet选项->安全->本地Internet->站点，把所有勾选取消
  hotClient: false
}

let moduleKeys = []
let moduleKey = ''

for(let key in modulesData) {
  moduleKey = key.split('.')[0]
  moduleKeys.push(moduleKey)
}

moduleKeys = [...new Set(moduleKeys)]
moduleKeys = moduleKeys.sort()

const moduleKeyMaxLength = getObjectItemMaxLength(moduleMap)

const promptList = [
  {
    type:'checkbox',
    message:'请选择启动的模块名称: ',
    name:'modules',
    choices:[
      {
        name: 'All: 所有模块',
        // 默认选中
        // checked: true
      },
      // 添加分隔符
      new inquirer.Separator('--- start 自定义模块 ---'),
      // 自定义模块名称
      ...moduleKeys.map(moduleKey => {
        return {
          name: `${completeString(moduleKey, moduleKeyMaxLength)}:  ${moduleMap[moduleKey]}`,
          checked: moduleKey == 'system'
        }
      }),
      // 添加分隔符
      new inquirer.Separator('--- start 自定义模块 ---'),
    ]
  }
]

inquirer.prompt(promptList).then(answers => {
  // 选择启动模块数据
  let modules = answers.modules
  
  modules = modules.map(moduleKey => {
    return moduleKey.split(':')[0].trim()
  })
  
  // 原始入口数据
  let originEntry = koaWebpackConfig.config.entry
  // 新入口数据
  let entry = {}
  
  // 是否为全部模块启动
  let isAll = modules.includes('All')
  if (isAll) {
    
    global.webpackConfig = {
      entry: originEntry
    }
    
    return start()
  }
  
  // 添加新入口数据
  for (let key in originEntry) {
    let entryKey = key.split('.')[0]
    if (modules.includes(entryKey)) {
      entry[key] = originEntry[key]
    }
  }
  
  // 用新入口配置数据覆盖配置项
  koaWebpackConfig.config.entry = entry
  let plugins = koaWebpackConfig.config.plugins || []
  plugins = plugins.filter(plugin => {
    return (plugin.options && !plugin.options.template) || !plugin.options
  })
  
  koaWebpackConfig.config.plugins = plugins.concat(util.genHtmlPlugins(entry))
  
  global.webpackConfig = {
    entry
  }
  
  // 启动
  start()
})

/**
 * @description: 启动
 * @return {void}
 */
function start() {
  koaWebpack(koaWebpackConfig).then(middleware => {
    middleware.devMiddleware.waitUntilValid(() => {

      server.use(middleware)
      server.init()
      
      // 启动server  outputs green text
      server.listen(9001, ()=> {
        const LISTEN_ADDRESSS = 'http://127.0.0.1:9001'
        console.log(`${colors.bgGreen('[本地地址]:') } ${LISTEN_ADDRESSS}`)
        process.platform === 'darwin' ? exec(`open  ${LISTEN_ADDRESSS}`) : exec(`start  ${LISTEN_ADDRESSS}`)
      })
    })
  })
}
